/**
 * 实现一个方法实现: 扁平结构和树结构转化:
 * 若当前项pid为和另一项的id匹配，则当前项放入另一项的到children中
 * 
 * 
 * 输入值:
 * [
 *   { id: 1, name: "部门1", pid: 0 },
 *   { id: 2, name: "部门2", pid: 1 },
 *   { id: 3, name: "部门3", pid: 1 },
 *   { id: 4, name: "部门4", pid: 3 },
 *   { id: 5, name: "部门5", pid: 4 }
 * ]
 *
 *
 * 输出值:
 * [
 *   {
 *     id: 1, name: '部门1', pid: 0,
 *     children: [
 *       { id: 2, name: '部门2', pid: 1 },
 *       { id: 3, name: '部门3', pid: 1,
 *         children: [
 *           { id: 4, name: '部门4', pid: 3,
 *             children: [
 *               { id: 5, name: '部门5', pid: 4 }
 *             ]
 *           }
 *         ]
 *       }
 *     ]
 *   }
 * ]
*/


function arrToTree(list) {
  const res = [];
  const map = list.reduce((res, v) => (res[v.id] = v, res), {});
  for (const item of list) {
    if (item.pid === 0) {
      res.push(item);
      continue;
    }
    if (item.pid in map) {
      const parent = map[item.pid];
      parent.children = parent.children || [];
      parent.children.push(item);
    }
  }
  return res;
}

// 测试
const flatArr = [
  { id: 1, name: "部门1", pid: 0 },
  { id: 2, name: "部门2", pid: 1 },
  { id: 3, name: "部门3", pid: 1 },
  { id: 4, name: "部门4", pid: 3 },
  { id: 5, name: "部门5", pid: 4 },
]
const treeArr = arrToTree(flatArr)

console.log(treeArr)
/**
 * [
 *   {
 *     id: 1, name: '部门1', pid: 0,
 *     children: [
 *       { id: 2, name: '部门2', pid: 1 },
 *       { id: 3, name: '部门3', pid: 1,
 *         children: [
 *           { id: 4, name: '部门4', pid: 3,
 *             children: [
 *               { id: 5, name: '部门5', pid: 4 }
 *             ]
 *           }
 *         ]
 *       }
 *     ]
 *   }
 * ]
*/
